﻿Imports System.IO
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.AspNetCore.Http
Imports Microsoft.AspNetCore.Routing

Public Class gMiddleware '网站服务器中间层件
    '首页初始化
    Shared Async Function gWebIndex(ByVal context As HttpContext, ByVal [next] As Func(Of Task), ByVal gIndexWebPath As String) As Task '默认首页设置
        Dim ep As String() = context.Request.Path.Value.Split("/")
        Dim epath As String = ep(UBound(ep))
        context.Response.ContentType = "application/json"
        Dim sf As String = gIndexWebPath
        For i = 1 To UBound(ep)
            sf = Path.Combine(sf, ep(i))
        Next
        sf = Path.Combine(sf, "index.html")
        If ep(1) = "ws" And UBound(ep) < 3 Then
            'WebSocket通道
            Await context.Response.WriteAsync("{""total"":""0"",""rows"":[],""err"":""1"",""msg"":""WebSocket通道，禁止访问！""}")
        Else
            '默认首页设置
            If epath = vbNullString Or epath.IndexOf("?") = 0 Or epath.IndexOf("#") = 0 Then
                If (IO.File.Exists(sf)) Then
                    context.Response.ContentType = "text/html; charset=utf-8"
                    Await context.Response.SendFileAsync(sf)
                Else
                    Await context.Response.WriteAsync("{""total"":""0"",""rows"":[],""err"":""1"",""msg"":""首页未找到！""}")
                End If
            Else
                Await [next]()
            End If
        End If
    End Function
    Shared Sub gWebTest(ByVal endpoints As IEndpointRouteBuilder, ByVal epath As String, ByVal conttype As String)
        endpoints.MapGet(epath, Async Function(context As HttpContext)
                                    context.Response.ContentType = conttype
                                    Await context.Response.WriteAsync("<p></p><p></p><p></p><center>无法访问！</center>")
                                End Function)
    End Sub
End Class
Public Class httperr 'HTTP错误
    Private [next] As RequestDelegate
    Public Sub New(ByVal n As RequestDelegate)
        [next] = n
    End Sub
    Public Async Function Invoke(context As HttpContext) As Task
        Await [next](context)
        Dim response As HttpResponse = context.Response
        Select Case response.StatusCode
            Case 404
                Await context.Response.WriteAsync("{""total"":""0"",""rows"":[],""err"":""1"",""msg"":""资源未找到！""}")
            Case 405
                Await context.Response.WriteAsync("{""total"":""0"",""rows"":[],""err"":""1"",""msg"":""无效的访问！""}")
        End Select
    End Function
End Class